<template>
    <div class="mod-config exam-box">
      <div class="exam-left">
        <paper-cate
          ref="paperCate"
          rootName="答题分类管理"
          :setCurrent="setCurrent"
          :current="current"
          :url="{
                                cateType: 1,
                                update:'/exam-admin/daily/cate/update',
                                save:'/exam-admin/daily/cate/save',
                                delete:'/exam-admin/daily/cate/delete',
                                tree:'/exam-admin/daily/cate/tree'
                                }"
        />
      </div>
      <div class="exam-right">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList(1)">
            <el-form-item>
                <el-input v-model="dataForm.dailyName" placeholder="请输入名称" clearable/>
            </el-form-item>
<!--            <el-form-item>-->
<!--              <el-date-picker-->
<!--                v-model="dataForm.date"-->
<!--                type="datetimerange"-->
<!--                range-separator="至"-->
<!--                start-placeholder="开始日期"-->
<!--                value-format="yyyy-MM-dd"-->
<!--                end-placeholder="结束日期">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
            <el-form-item>
                <el-button @click="getDataList(1)">查询</el-button>
                <el-button type="primary" @click="addHandle()">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="dataList" border style="flex: 1" height="100%" v-loading="dataListLoading">
            <el-table-column
                    prop="ID"
                    type="index"
                    header-align="center"
                    align="center"
                    width="80"
                    label="ID"
            />
            <el-table-column prop="name" header-align="center" align="center" label="名称"/>
          <el-table-column prop="startTime" header-align="center" align="center" label="开始时间">
            <template slot-scope="scope">
              <span v-if="scope.row.startTime">{{scope.row.startTime}}</span>
              <span  v-else> ~ ~ </span>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" header-align="center" align="center" label="结束时间">
            <template slot-scope="scope">
              <span v-if="scope.row.endTime">{{scope.row.endTime}}</span>
              <span  v-else> ~ ~ </span>
            </template>
          </el-table-column>
            <el-table-column prop="createTime" header-align="center" align="center" label="创建时间"/>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                <template slot-scope="scope">
                  <el-button  type="text"
                             @click="addHandle(scope.row.id,parseInt(scope.row.currentMonth) === 1)">修改
                  </el-button>
                  <el-button type="text" v-if="parseInt(scope.row.status) !== 0" @click="getpoints(scope.row.id, 400000)">积分设置</el-button>
                    <!--<el-button type="text" @click="addHandle(scope.row.id)">管理</el-button>-->
                    <el-button type="text" @click="deleteHandle(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page="pages.page"
                :page-sizes="[10, 20, 50]"
                :page-size="pages.limit"
                :total="totalPage"
                layout="total, sizes, prev, pager, next, jumper"
        />

        <!-- 弹窗, 新增 / 修改 -->
        <add-exam
                v-if="isAddExam"
                ref="addExam"
                :isMonth="true"
                :url="{
          info: `/exam-admin/exam/daily/info`,
          save: `/exam-admin/exam/daily/save`,
          update: `/exam-admin/exam/daily/update`}"
                :getExam="getExam"
        />

        <el-drawer
                title="指定参加人员"
                custom-class="drawer-box"
                :append-to-body="true"
                :visible="dailyQuestionDrawer"
                size="80%"
                :close-on-press-escape="false"
                :show-close="false"
                :wrapperClosable="false"
                v-loading="loading"
        >
            <el-row :gutter="20" style="margin: 0">
                <el-col :span="6" :offset="18" class="learn-drawer-range-box-buttons">
                    <el-button
                            class="el-icon-check"
                            type="text"
                            @click="onSubmit"
                            style="color: #67C23A;font-size:24px"
                    />
                    <el-button
                            class="el-icon-close"
                            type="text"
                            @click="onClose"
                            style="color: #F56C6C;font-size: 24px"
                    />
                </el-col>
            </el-row>
            <el-form ref="questionForm" :model="questionForm" :rules="questionRule">
                <exam-type
                        ref="examType"
                        :setUserList="setUserList"
                        :form="questionForm"
                        :examTypeChange="examTypeChange"
                        :examUserArrClose="examUserArrClose"
                        :setLoading="setLoading"
                        :handleSelectionChange="handleSelectionChange"
                />
            </el-form>
        </el-drawer>

        <Setpoints ref="setpoints"></Setpoints>
      </div>
    </div>
</template>

<script>
  import AddExam from '../../../components/check/addExam'
  import paperCate from './../paper/papercate'
  import ExamType from '../../../components/examType/exam-type'
  import Setpoints from '../exam/setpoints'

  export default {
    name: 'daily-question',
    components: {ExamType, AddExam, paperCate, Setpoints},
    data () {
      return {
        setUserList: [],
        isAddExam: false,
        pages: {
          page: 1,
          limit: 10
        },
        totalPage: 0,
        dataForm: {
          dailyName: '',
          date: [],
          startTime: '',
          endTime: ''
        },
        current: {},
        dataList: [],
        dataListLoading: false,
        dailyQuestionDrawer: false,
        loading: false,
        questionForm: {
          examType: 0,
          dailyQuesCount: 1,
          userIds: ''
        },
        questionRule: {
          userIds: [
            {required: true, message: '指定人员不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
      this.getDataList()
      this.$refs.paperCate.init()
    },
    methods: {
      getpoints(id, pCode) {
        this.$nextTick(_ => this.$refs.setpoints.init(id, pCode))
      },
      setCurrent(data, bool) {
        if (bool && data.id) {
          this.current = data
          this.dataForm.cateId = data.id
          this.getDataList(1)
        }
      },
      initSearchForm (obj) {
        this.$refs.examType.$refs.searchForm.init(obj)
      },
      examTypeChange (val) {
        this.questionForm.examType = val
        if (val) {
          this.initSearchForm({
            userIds: this.setUserList.map(x => x.userId).join(',')
          })
        }
      },
      examUserArrClose (item, index) {
        this.setUserList.splice(index, 1)
        this.searchFormInit()
      },
      setLoading (val) {
        this.loading = val
      },
      handleSelectionChange (val) {
        if (val.length) {
          this.setUserList = this.setUserList.concat(val)
          this.searchFormInit()
        }
      },
      searchFormInit () {
        this.$refs.examType.$refs.searchForm.search({
          userIds: this.setUserList.map(x => x.userId).join(',')
        })
      },
      getExam (val, noEdit) {
        let startTime = val.startTime
        let endTime = val.endTime
        // let date = val.date.split('-')
        if (val.setUserList && val.setUserList.length) {
          if (noEdit) {
            val.setUserList.forEach(x => {
              x.isEdit = true
            })
          }
          this.setUserList = val.setUserList
        } else {
          this.setUserList = []
        }
        this.questionForm = {
          id: val.id || '',
          cateId: val.cateId,
          compType: val.compType,
          endTime: endTime,
          quesCateIds: val.quesCateIds,
          quesRange: val.quesRange,
          isTimeRange: val.isTimeRange,
          dailyQuesCount: val.dailyQuesCount,
          name: val.paperName,
          startTime: startTime,
          intervalDay: val.intervalDay,
          everyTimeAnswNum: val.everyTimeAnswNum,
          answType: val.answType,
          answUpperLimit: val.answUpperLimit,
          examType: val.examType || 0,
          userIds: this.setUserList.map(x => x.userId).join(','),
          quesDisorder: val.quesDisorder,
          publisherType: val.publisherType,
          status: val.status
        }

        if (parseInt(val.compType) === 0) {
          if (JSON.parse(val.paperInfo).length) {
            this.questionForm.paperInfo = JSON.stringify(JSON.parse(val.paperInfo).map((x, i) => ({
              quesId: x.id,
              sort: i
            })))
          } else {
            this.questionForm.paperInfo = ''
          }
        } else {
          this.questionForm.paperInfo = val.paperInfo
        }
        this.dailyQuestionDrawer = true
      },
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/exam-admin/exam/daily/list'),
          method: 'post',
          // data: Object.assign(this.dataForm, this.pages)
          data: {
            cateId: this.dataForm.cateId,
            startTime: this.dataForm.date[0],
            endTime: this.dataForm.date[1],
            dailyName: this.dataForm.dailyName,
            page: this.pages.page,
            limit: this.pages.limit
          }
        }).then(({data}) => {
          if (data) {
            this.dataList = data.list
            this.totalPage = data.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      addHandle (id, noEdit = false) {
        this.isAddExam = true
        this.$nextTick(_ => this.$refs.addExam.init(id, noEdit, 3))
      },
      // 删除
      deleteHandle (id) {
        this.$confirm(`确定要进行删除操作吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl(`/exam-admin/exam/daily/delete/${id}`),
            method: 'post'
          }).then(res => {
            if (res && res.code === 200) {
              this.$notify.success({
                title: '提示',
                message: '操作成功'
              })
              this.getDataList()
              // this.page.page > 1 && this.dataList.length <= 1 && this.pages.page --
            } else {
              this.$notify.error({
                title: '提示',
                message: res.msg
              })
            }
          })
        })
      },
      onSubmit () {
        if (this.setUserList.length) {
          this.questionForm.userIds = this.setUserList
            .map(x => x.userId)
            .join(',')
        }
        this.$refs['questionForm'].validate(valid => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(
                `/exam-admin/exam/daily/${
                  this.questionForm.id ? 'update' : 'save'
                }`
              ),
              method: 'post',
              data: Object.assign({}, this.questionForm, {
                publisherType: this.questionForm.examType
              })
            })
              .then(res => {
                if (res && res.code === 200) {
                  this.$notify.success({
                    title: !this.questionForm.id ? '新增' : '更新',
                    message: '操作成功'
                  })
                  parseInt(this.questionForm.compType) === 0
                    ? sessionStorage.removeItem('examData')
                    : sessionStorage.removeItem('topic')
                  this.$refs.addExam.examData = {}
                  this.loading = false
                  this.$refs.addExam.examDialogVisible = false
                  this.onClose()
                  this.getDataList()
                } else {
                  this.$notify.error({
                    title: '错误',
                    message: res.msg
                  })
                }
                this.loading = false
              })
              .catch(_ => {
                this.loading = false
              })
          }
        })
      },
      onClose () {
        this.questionForm = {
          userIds: '',
          examType: 0
        }
        this.setUserList = []
        this.$refs.examType.pagination = {
          page: 1,
          limit: 10
        }
        this.dailyQuestionDrawer = false
      },
      sizeChangeHandle (val) {
        this.pages = {
          limit: val,
          page: 1
        }
        this.getDataList()
      },
      currentChangeHandle (val) {
        this.pages.page = val
        this.getDataList()
      }
    }
  }
</script>
<style lang="scss">
  .exam-box {
    height: 100%;
    display: flex;
    overflow: auto;
    border: 1px solid #eee;

  .exam-left {
    padding-right: 10px;
  }

  .exam-right {
    padding: 10px;
    overflow: auto;
    flex: 1;
  }
  }
</style>
